package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

/**
 * @author lfy
 * @Description
 * @create 2023-07-15 16:48
 */
public class JSONs {

    private static final ObjectMapper objectMapper = new ObjectMapper();


    public static String obj2JsonStr(Object obj){
        try {
            String value = objectMapper.writeValueAsString(obj);
            return value;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static<T> T jsonStr2Obj(String json, Class<T> valueTypeRef) {
        T t = null;
        try {
            if(StringUtils.isEmpty(json)) return null;
            t = objectMapper.readValue(json, valueTypeRef);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }

    public static<T> T jsonStr2Obj(String json, TypeReference<T> valueTypeRef) {
        T t = null;
        try {
            if(StringUtils.isEmpty(json)) return null;
            t = objectMapper.readValue(json, valueTypeRef);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
}
